package com.dly.hope.listener;

import com.dly.hope.constant.RedisConstant;
import com.dly.hope.modle.WebSocketMemberMessage;
import com.dly.hope.modle.WebSocketMessage;
import com.dly.hope.servce.SaveService;
import com.dly.hope.utils.JsonFormatUtil;
import com.dly.hope.type.MessageType;
import com.dly.hope.webSocket.WebSocketServer;
import com.dly.hope.webSocket.dto.MessageDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Objects;

/**
 * @author linyu.dai
 * @project myserve
 * @description 消息处理
 * @creat 2022/11/8 10:49:01
 */
@Component
@Slf4j
public class RedisReceiver implements MessageListener {

    @Resource
    private SaveService saveService;

    @Override
    public void onMessage(Message message, byte[] pattern) {

        String ms = new String(message.getBody());

        String pa = new String(pattern);

        if(!StringUtils.isEmpty(ms) && !StringUtils.isEmpty(pa)){
            if(pa.equals(RedisConstant.MESSAGE_CHANNEL)) {
                log.info("保存信息-----{}", message);
                //这两个是一样的 getChannel 和 pattern 都是渠道名字
                MessageDto messageDto = JsonFormatUtil.readFromJsonString(ms, MessageDto.class);
                //保存信息
                WebSocketMessage webSocketMessage = saveService.saveWebSocketMessage(messageDto);

                saveService.saveWebSocketMemberMessage(messageDto, webSocketMessage);

                //发送信息
                WebSocketServer.sendMessage(new String(message.getBody()), messageDto.getAcceptUserSocketDto().getUserId());
            }
        }
    }

}
